<?php
/**
 * 农田
 *
 * Created	: 2010-10-14
 * Modified : 2010-10-18
 * @author  : 陈立强
 */
class Farm
{

	public static $info = null;
	public static $proficiencyType = 1;
	public static $cfg = null;
	public static $cfgName = 'build/farm';

	/**
	 * 初始化玩家的农田耕地信息
	 * @param int $uid
	 */
	public static function init ($uid)
	{
		global $DB, $L;
		if (!$uid) {
			return false;
		}

		$data = array();
		$lvl = 0;

		$cfg = C('build/farm');
		$plowlandNum = $cfg[$lvl]['plowland_num'];

		$DB->beginTransaction();
		for ($pos=1; $pos<=$plowlandNum; $pos++) {
			// 更新数据
			$data = array(
				'uid'       => $uid,
				'pos'       => $pos,
				'now_crop'  => 0,
				'ripe_time' => 0,
				'num'		=> '',
				'fit_crop'  => 0,
				'fit_exp'   => 0,
				'status'	=> 0,
				'is_weeded' => 0,
			);
			$ret = $DB->insert('farm', $data);
			if (!$ret) {
				$DB->rollBack();
				break;
			}
		}
		if ($ret) {
			$DB->commit();
		}
		return $ret;
	}

	/**
	 * 获取一块耕地的信息
	 * @param int $uid 用户ID
	 * @param int $pos 耕地的位置
	 * @param int $updateRipeInfo 是否同时更新已成熟的作物信息
	 */
	public static function getPlowlandInfo($uid, $pos, $updateRipeInfo=1)
	{
		global $DB, $L;
		$sql = 'SELECT * FROM farm WHERE uid=:uid and pos=:pos';
		$params = array('pos'=>(int)$pos, 'uid'=>(int)$uid);
		$info = self::$info = $DB->getValue($sql, $params);
		if (false === $info) {
			return array(
				'val' => false,
				'msg' => $L['farm_isnot_assarted']
			);
		}
		$now = time();
		if ($updateRipeInfo && $info['ripe_time']<=$now && $info['num']=='') {
			$ret = self::mature($uid, $pos);
			if ($ret['val']) {
				$info['num'] = $ret['data']['num'];
			}
		}
		if ($info['ripe_time'] > $now) {
			$info['ripe_time'] = $info['ripe_time'];
		} elseif ($info['ripe_time'] < $now) {
			$info['ripe_time'] = 0;
		}
		if (is_string($info['num'])) {
			$info['num'] = json_decode($info['num'], true) ;
		}
		$cropList = C('item/crop');
		if ($info['now_crop'] > 0) {
			$cfg = $cropList[$info['now_crop']];
			$info['title'] = $cfg['title'];
			$info['seed_id'] = $cfg['seed_id'];
		} else {
			$info['title'] = '';
		}
		if ($info['fit_crop']) {
			$info['fit_title'] = $cropList[$info['fit_crop']]['title'];
		} else {
			$info['fit_title'] = '';
		}
		return $info;
	}

	/**
	 * 获取农田等级
	 * @param int $uid 用户ID
	 */
	public static function getLvl($uid)
	{
		global $DB;
		$sql = 'SELECT farm_lvl FROM user WHERE uid='.(int)$uid;
		return (int)$DB->getValue($sql);
	}

	/**
	 * 获取农田信息
	 * @param int $uid
	 */
	public static function getInfo($uid)
	{
		global $DB, $L, $G;
		$farmLvl = self::getLvl($uid);
		$farm    = C('build/farm');

		$result['val'] = $farmLvl!==false ? true : false;
		if ($farmLvl !== false) {
			$result['data'] = $farm[$farmLvl];
			$result['data']['lvl'] = $farmLvl;
			$result['data']['farm_max_fit_val'] = $G['farm_max_fit_val'];
		} else {
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_get_info', $data);
		}
		return $result;
	}

	/**
	 * 获取所有耕地信息
	 * @param int $uid
	 * @param int $to_uid 获取他人的列表
	 */
	public static function getList($uid, $to_uid=null)
	{
		global $DB, $L, $max_plowland_num;

		$to_uid = (int)$to_uid;
		if ($to_uid) {
			$uid = $to_uid;
		}
		$sql     = 'SELECT * FROM farm WHERE uid='.(int)$uid;
		$tmpList = $DB->getList($sql);

		$list = array();
		$now = time();

//		$refreshTime = $now + 86400;// 刷新时间先设置成明天这时(实际时间都比这个短)
		$cfgList = C('item/crop');
		foreach($tmpList as $record) {
			if (empty($record['num']) && $record['ripe_time']>0 && $record['ripe_time'] <= $now) {
				$ret = self::mature($uid, $record['pos']);
				if ($ret['val']) {
					$record['num'] = $ret['data']['num'];
					$record['status'] = $ret['data']['status'];
				}
			} elseif ('' != $record['num']) {
				$record['num'] = json_decode($record['num'], true) ;
			}
			if (is_string($record['num'])) {
				$record['num'] = json_decode($record['num'], true) ;
			}
			$cfg = $cfgList[$record['fit_crop']];
			if ($record['now_crop']) {
				$record['title'] = $cfg['title'];
				$record['seed_id'] = $cfg['seed_id'];
			}
			if ($record['fit_crop']) {
				$record['fit_title'] = $cfg['title'];
			} else {
				$record['fit_title'] = '';
			}
			$list[$record['pos']] = $record;
//			if ($record['ripe_time'] > 0) {
//				$refreshTime = min($refreshTime, $record['ripe_time']);
//			}
		}
		return array(
			'val'  => true,
			'data' => $list
//			'data' => array(
//				'list' => $list,
//				'refresh_time' => $refresh_time
//			)
		);
	}

	/**
	 * 农田扩建
	 * @param int $uid
	 */
	public static function extend($uid)
	{
		global $DB, $L;

		$sql = 'SELECT ticket,farm_extend_times FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);

		$cfg = C('common/need_ticket');
		if ($user['farm_extend_times'] >= $cfg['farm_max_extend']) {
			return array(
				'val' => false,
				'msg' => $L['farm_extend_time_is_max']
			);
		}

		$needTicket = $cfg['farm_extend_need'][$user['farm_extend_times']+1];
		// 点券不足
		if ($needTicket > $user['ticket']) {
			return array(
				'val' => false,
				'msg' => $L['ticket_not_enough']
			);
		}

		$DB->beginTransaction();
		// 将扩建次数加1,且扣除对应的点券
		$sql = 'UPDATE user SET ticket=ticket-'.$needTicket.',farm_extend_times=farm_extend_times+1 WHERE uid='.$uid;
		$ret = $DB->exeSql($sql);
		if ($ret !== false) {
			$ret = true;
		}

		// 增加一块农田
		if ($ret) {
			$sql = 'SELECT MAX(pos) FROM farm WHERE uid='.$uid;
			$pos = $DB->getValue($sql);
			$data = array(
				'uid'       => $uid,
				'pos'       => $pos + 1,
				'now_crop'  => 0,
				'status'  	=> 0,
				'ripe_time' => 0,
				'num'     	=> '',
				'fit_crop'  => 0,
				'fit_exp'   => 0,
				'is_weeded' => 0,
			);
			$ret = $DB->insert('farm', $data);
		}

		$result['val'] = (bool)$ret;
		if ($ret) {
			// 处理成功,提交事务
			$DB->commit();
			$ret = self::getList($uid);
			$result['data'] = $ret['data'];
		} else {
			// 出错,回滚数据操作
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_extend', $data);
		}

		return $result;
	}

	/**
	 * 升级(增筑农田)
	 * @param int $uid
	 * @return boolean
	 */
	public static function lvlUp($uid)
	{
		global $DB, $L;

		$uid = (int)$uid;
		$lvl = self::getLvl($uid);
		$nextLvl = $lvl+1;

		$cfg = self::$cfg;

		// 是否已升级至满级
		end($cfg);
		$maxLvl = key($cfg);
		if ($nextLvl>$maxLvl) {
			return array(
				'val' => false,
				'msg' => $L['farm_is_max_lvl']
			);
		}

		$user = User::read($uid);
		// 需要金钱不足
		if ($user['coin'] < $cfg[$lvl]['need_coin']) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		// 角色等级是否满足
		if ($user['lvl'] < $cfg[$lvl]['need_mc_lvl']) {
			return array(
				'val' => false,
				'msg' => $L['mc_lvl_is_not_enough'].$lvl
			);
		}

		$DB->beginTransaction();

		$data = array(
			'farm_lvl' => $nextLvl
		);
		$ret = $DB->update('user', $data, 'uid='.$uid);

		// 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$cfg[$lvl]['need_coin'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}

		$result['val'] = (boolean)$ret;
		if ($ret) {
			// 增加新耕地
			$data    = array();
			$plowlandNum     = $cfg[$lvl]['plowland_num'];
			$nextPlowlandNum = $cfg[$nextLvl]['plowland_num'];


			$insert = 1;
			$sql = 'SELECT MAX(pos) FROM farm WHERE uid='.$uid;
			$pos = $DB->getValue($sql);
			$addPos = $nextPlowlandNum - $plowlandNum;
			for ($i=1; $i<=$addPos; $i++) {
				$pos += $i;
				// 更新数据
				$data = array(
					'uid'       => $uid,
					'pos'       => $pos,
					'now_crop'  => 0,
					'status'  	=> 0,
					'ripe_time' => 0,
					'num'     	=> '',
					'fit_crop'  => 0,
					'fit_exp'   => 0,
					'is_weeded' => 0,
				);
				$ret = $DB->insert('farm', $data);
				if (!$ret) {
					$insert = 0;
					$DB->rollBack();
					$result['val'] = (boolean)$ret;
					$result['msg'] = $L['Failure'];
					$data = var_export($DB->errors, true);
					// 记录错误日志
					Log::save('farm_lvl_up', $data);
					break;
				}
			}
			if ($insert) {
				$DB->commit();
				$ret = self::getList($uid);
				$result['data'] = $ret['data'];
			}
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_lvl_up', $data);
		}
		return $result;
	}

	/**
	 * 种植作物
	 * @param int $uid
	 * @param int $seedId 种子ID
	 * @param int $pos
	 */
	public static function plant($uid, $seedId, $pos)
	{
		global $DB, $L, $G;
		$info = self::getPlowlandInfo($uid, $pos, 0);
		if (isset($info['val']) && false === $info['val']) {
			return array(
				'val' => false,
				'msg' => $L['farm_isnot_assarted']
			);
		}

		//-- 对应位置的耕地是否有作物
		if ($info['now_crop']) {
			return array(
				'val' => false,
				'msg' => $L['farm_is_planted']
			);
		}

		//-- 种子不存在
		$cfgList = C('item/seed_list');
		if (!isset($cfgList[$seedId])) {
			return array(
				'val' => false,
				'msg' => $L['no_such_seed']
			);
		}
		$cropId = $cfgList[$seedId];
		$cfgList = C('item/crop');
		$cfgInfo = $cfgList[$cropId];

		// 作物信息
		if (empty($cfgInfo)) {
			return array(
				'val' => false,
				'msg' => $L['no_such_crop']
			);
		}

		//-- 前置熟练度等级是否达到要求
		if ($cfgInfo['pre_product']) {
			$sql = 'SELECT lvl FROM user_proficiency WHERE uid='.$uid.' AND item_id='.$cfgInfo['pre_product'];
			$lvl = $DB->getValue($sql);
			if (!$lvl || $lvl < $G['pre_proficiency_lvl']) {
				return array(
					'val' => false,
					'msg' => $L['pre_product_lvl_not_enough']
				);
			}
		}

		//-- 季节是否满足种子的种植要求
		$plant_season = $cfgInfo['plant_season'];
		if (false === strpos($plant_season, (string)Game::$data['season'])) {
			return array(
				'val' => false,
				'msg' => $L['crop_cannot_plant_now_season']
			);
		}

		$sql = 'SELECT lvl,coin FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
		//-- 牧场等级是否达到要求(不再需要)
//		if ($user['lvl'] < $cfgInfo['need_mc_lvl']) {
//			return array(
//				'val' => false,
//				'msg' => $L['mc_lvl_is_not_enough']
//			);
//		}

		//-- 是否有足够的金钱
		if ($user['coin'] < $cfgInfo['seed_price']) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}

		//-- 是否有足够的种子
//		$sql = 'SELECT depot_id,num FROM depot WHERE uid=:uid and item_id=:item_id';
//		$params = array(
//			'uid'     => $uid,
//			'item_id' => $seedId,
//		);
//		$itemInfo = $DB->getValue($sql, $params);
//		$num = $itemInfo['num'];
//		if ($num <= 0) {
//			return array(
//				'val' => false,
//				'msg' => $L['seed_isnot_enough']
//			);
//		}


		$DB->beginTransaction();

		// 种植该作物成熟需要时间
		$needTime = $cfgInfo['plant_need_time'];
		// 作物要成熟的时间点
		$ripeTime = time() + $needTime;

		// 种植与适应作物不同的作物,适应度等级清零
		if ($info['fit_crop'] != $cropId) {
			$fitCrop = $cropId;
			$fitExp  = 0;
		} else {
			$fitCrop = $cropId;
			$fitExp  = $info['fit_exp'];
		}

		// 更新耕地信息
		$data = array(
			'now_crop'  => $cropId,
			'status'	=> 1,
			'fit_crop'  => $fitCrop,
			'ripe_time' => $ripeTime,
			'num'     => '',
			'fit_exp'   => $fitExp,
		);
		$where = 'fid='.$info['fid'];
		$ret = $DB->update('farm', $data, $where);

		//-- 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$cfgInfo['seed_price'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}

		$result['val'] = (bool)$ret;
		if ($ret) {
			// 处理成功,提交事务
			$DB->commit();
			$itemList = C('item/titem');
			$info['title'] = $itemList[$cropId]['title'];
			$info['fit_title'] = $itemList[$fitCrop]['title'];
			$data['ripe_time'] = $ripeTime;
			$result['data'] = $data + $info;
		} else {
			// 出错,回滚数据操作
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_plant', $data);
		}

		return $result;
	}

	/**
	 * 使作物成熟
	 * @param int $uid 用户ID
	 * @param int $pos 耕地的位置
	 */
	public static function mature($uid, $pos)
	{
		global $DB, $L, $G;

		if (self::$info) {
			$info = self::$info;
		}

		if (!self::$info || self::$info['pos'] != $pos) {
			$info = self::getPlowlandInfo($uid, $pos, 0);
		}

		if ($info['now_crop'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['plowland_hasno_crop']
			);
		}

		// 已经生成成熟的数据
		if ($info['num'] != '') {
			return array(
				'val'  => true,
				'data' => array(
					'num' => $info['num']
				)
			);
		}

		// 未到成熟时间
		if ($info['ripe_time'] > time()) {
			return array(
				'val' => false,
				'msg' => $L['crop_hasnot_ripe']
			);
		}

		//-- 生成成熟的作物及数量
		$cfgList     = C('item/crop');
		$baseOutput  = $cfgList[$info['now_crop']]['base_output'];
		// 适应度加成 = 适应度*参数
		$fitAddition = $info['fit_exp'] * $G['farm_fit_param'];
		$rnd = round(rand (60, 100)/100, 2);
		$output = ($baseOutput + $fitAddition + $info['fertilize']) * $rnd;
		// 根据最终产量数量取配置结果
		$outputCfg = C('output/crop_output');
		$num = getRangeKeyValue($output, $outputCfg);
		$numStr = json_encode($num);

		$data = array(
			'status' => 2,
			'num' => $numStr
		);
		$where = 'fid='.(int)$info['fid'];
		$ret = $DB->update('farm', $data, $where);
		$result['val'] = $ret;
		if ($ret) {
			$result['data'] = array(
				'num'	=> $num,
				'status'=> 2
			);
		} else {
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_mature', $data);
		}
		self::$info = null;
		return $result;

	}

	/**
	 * 收割指定耕地的作物
	 * @param int $uid 用户ID
	 * @param int $pos 耕地的位置
	 */
	public static function harvest($uid, $pos)
	{
		global $DB, $L, $G;

		if (empty(self::$info)) {
			$info = self::getPlowlandInfo($uid, $pos, 1);
		} else {
			$info = self::$info;
		}

		if (isset($info['val']) && false === $info['val']) {
			return array(
				'val' => false,
				'msg' => $L['farm_isnot_assarted']
			);
		}

		// 耕地是空的，没有作物
		if ($info['now_crop'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['plowland_hasno_crop']
			);
		}

		// 未到成熟时间
		if ($info['ripe_time'] > time()) {
			return array(
				'val' => false,
				'msg' => $L['crop_hasnot_ripe']
			);
		}
		
		$freeCapacity = Depot::getFreeCapacity($uid);
		// 仓库容量不足
		if ($freeCapacity == 0) {
			return array(
				'val' => false,
				'msg' => $L['not_enough_grid_in_depot']
			);
		}
		// 产品是否全部收获
		$allHarvest = ($freeCapacity >= array_sum($info['num']));

		//-- 收获增加适应度
		if ($allHarvest) {
			$cfg = self::$cfg;
			$lvl = self::getLvl($uid);
			$fitExp = $info['fit_exp'] + rand($G['harvest_add_fit_val'][0], $G['harvest_add_fit_val'][1]);
			if ($fitExp > $G['farm_max_fit_val']) {
				$fitExp = $G['farm_max_fit_val'];
			}
		} else {
			$fitExp = 0;
		}

		$DB->beginTransaction();

		$ret = false;

		$cropList = C('item/crop');
		$cropInfo = $cropList[$info['now_crop']];
		//-- 收获物品进入仓库
		$qualityCfg = $G['id_quality'];
		$harvest = array();
		// 产品从小到大进行收获
		ksort($info['num']);
		foreach ($info['num'] as $quality => $num) {
			if ($num == 0) {
				unset($info['num'][$quality]);
				continue;
			}
			if ($freeCapacity == 0) {
				break;
			}
			if ($freeCapacity < $num) {
				$num = $freeCapacity;
				$info['num'][$quality] -= $num;
			} else {
				unset($info['num'][$quality]);
			};
			$data = array(
				'title'		=> $info['title'],
				'item_id'	=> $info['now_crop'],
				'item_type' => $cropInfo['item_type'],
				'num'		=> $num,
				'quality'	=> $quality,
				'lvl'		=> $cropInfo['lvl']
			);

			$ret = Depot::in($uid, $data);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			}
			$harvest[$quality] = $num;
			
			// 当前收获后已经没有容量 了
			$freeCapacity -= $num;
			if ($freeCapacity == 0) {
				break;
			}
		}

		$DB->setTransactionState(false);
		//-- 收获获得种植熟练度
		if ($ret && $allHarvest && $info['now_crop']!=100) {
			$proExp = $cropInfo['add_proficiency'];// 获取的熟练度值
			$ret = User::addProficiency($uid, $proExp, $info['now_crop'], 1);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			} else {
				$ret = true;
			}
		}
		//-- 收获获得经验
		if ($ret && $allHarvest) {
			$exp = $cropInfo['add_exp'];
			$ret = User::addExp($uid, $exp);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			} else {
				$ret = true;
			}
		}

		// 是否可以获取惊喜宝箱
		$getTreasureBox = false;
		$inMail = false;
		if ($ret && $allHarvest && getRandResult($G['harvest_get_box_rate'])) {
//		if ($ret) {
			$item_id = 11006;
			$lvl = 0;
			$mailContent = sprintf($L['harvest_get_box'], $info['title']);
			$return = TreasureBox::get($uid, $item_id, $lvl, null, $mailContent);
			$ret = $return['val'];
			$inMail = $return['data']['in_mail'];
			$getTreasureBox = true;
		} else {
			$inMail = false;
			$getTreasureBox = false;
		}
		$DB->setTransactionState(true);

		//-- 修改耕地信息
		if ($ret) {
			// 全部收获清空耕地信息
			if ($allHarvest) {
				$data = array(
					'status'	=> 0,
					'now_crop'	=> 0,
					'ripe_time'	=> 0,
					'num'		=> '',
					'fit_exp'	=> $fitExp,
					'fertilize'	=> 0,
				);
			} else {
				$data = array(
					'num'	=> json_encode($info['num']),
				);
			}
			$where = 'fid='.(int)$info['fid'];
			$ret = $DB->update('farm', $data, $where);
			if ($ret !== false) {
				$ret = true;
			}
		}

		$result['val'] = $ret;
		if ($ret) {
			$DB->commit();
			$info['fit_title'] = $cropList[$info['fit_crop']]['title'];
			$result['data'] = $data + $info;
			$result['data']['get_treasure_box'] = $getTreasureBox;
			$result['data']['in_mail'] = $inMail;
			$result['data']['all_harvest'] = $allHarvest;
			if (!$allHarvest) {
				$result['data']['harvest'] = $harvest;
			}
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_harvest', $data);
		}
		return $result;
	}

	/**
	 * 获取种子列表
	 * @param $uid
	 */
	public static function getSeedList($uid)
	{
		return Town::getCropSeedList($uid);
	}

	/**
	 * 获取化肥列表
	 * @param $uid
	 */
	public static function getFertiliserList($uid)
	{
		global $DB, $L;

		$sql = 'SELECT depot_id,item_id,title,num FROM depot WHERE uid='.$uid.' AND item_type=31';
		$list = $DB->getList($sql);

		if (!$list) $list = array();
		$data = array();
		foreach ($list as $k=>$item) {
			$data[] = $item;
		}

		return array(
			'val' => true,
			'data' => $data,
		);
	}

	/**
	 * 施肥
	 * @param int $uid 用户ID
	 * @param int $pos 耕地的位置
	 * @param int $box_id 化肥的道具箱ID
	 */
	public static function fertilize($uid, $pos, $box_id)
	{
		global $DB, $L, $G;

		$box_id = (int)$box_id;
		$sql = 'SELECT uid,item_id,item_type,num FROM props_box WHERE box_id='.$box_id;
		$boxInfo = $DB->getValue($sql);
		//-- 是否有足够的化肥;
		if (!$boxInfo) {
			return array(
				'val' => false,
				'msg' => $L['item_not_enough']
			);
		}
		// 不是化肥
		if ($boxInfo['item_type']!=31 || $boxInfo['uid']!=$uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}

		$info = self::getPlowlandInfo($uid, $pos);
		if (isset($info['val']) && false === $info['val']) {
			return array(
				'val' => false,
				'msg' => $L['farm_isnot_assarted']
			);
		}
		// 是否有作物
		if ($info['now_crop'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['plowland_hasno_crop']
			);
		}

		// 是否已经成熟了
		if ($info['status'] == 2) {
			return array(
				'val' => false,
				'msg' => $L['crop_had_riped_cannot_to_fertilize']
			);
		}

		// 是否已经施肥过了
		if ($info['fertilize'] > 0) {
			return array(
				'val' => false,
				'msg' => $L['this_farm_had_fertilized']
			);
		}

		$cfg = C('item/fertiliser');
		$cfg = $cfg[$itemInfo['item_id']];

		$DB->beginTransaction();

		// 扣除一个化肥
		if ($boxInfo['num'] > 1) {
			$sql = 'UPDATE props_box SET num=num-1 WHERE box_id='.$box_id;
		} else {
			$sql = 'DELETE FROM props_box WHERE box_id='.$box_id;
		}
		$ret = $DB->exeSql($sql);
		if ($ret !== false) {
			$ret = true;
		}

		if ($ret) {
			$data = array(
				'fertilize' => $cfg['add_output']
			);
			$ret = $DB->update('farm', $data, 'uid='.$uid.' and pos='.$pos);
		}

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = $data + $info;
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_harvest', $data);
		}
		return $result;
	}

	/**
	 * 铲除
	 * @param int $uid 用户ID
	 * @param int $pos 耕地的位置
	 */
	public static function eradicate($uid, $pos)
	{
		global $DB, $L, $G;

		$DB->beginTransaction();

		$data = array(
			'status'	=> 0,
			'now_crop'	=> 0,
			'ripe_time'	=> 0,
			'num'		=> '',
			'fertilize'	=> 0
		);
		$pos = (int)$pos;
		$ret = $DB->update('farm', $data, 'uid='.$uid.' and pos='.$pos);
		$ret!==false && $ret = true;

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getPlowlandInfo($uid, $pos);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_eradicate', $data);
		}
		return $result;
	}
	
	/********************************************
	 * 互动部分
	 ********************************************/
	
	/**
	 * 偷窃
	 * @param int $uid
	 * @param int $to_uid
	 * @param int $pos
	 */
	public static function steal($uid, $to_uid, $pos) 
	{
		global $DB, $L, $G;
		
		if ($uid == $to_uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$userInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time,energy_point,in_prison');
		if ($userInfo['in_prison']) {
			$sql = 'SELECT * FROM prison WHERE uid='.$uid;
			$prisonInfo = $DB->getValue($sql);
			if (!$prisonInfo['can_interactive']) {
				return array(
					'val' => false,
					'msg' => $L['cannot_steal_in_prison']
				);
			}
		}
		
		// 能量点不够
		if (!$userInfo['energy_point']) {
			return array(
				'val' => false,
				'msg' => $L['energy_point_not_enough']
			);
		}
		
		// 判断是否好友
		if (!Friend::isFriend($uid, $to_uid)) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$posInfo = self::getPlowlandInfo($to_uid, $pos);
		// 还未成熟,不能偷窃
		if ($posInfo['status'] != 2) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 已经被偷过了
		if ($posInfo['is_stolen']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$now = time();
		
		$toUserInfo = User::read($to_uid, 'lvl,seriate_steal_times');
		
		// 载入互动操作配置
		C('common/interactive');
		
		// 上次偷窃时间到现在超过24小时,连续偷窃次数清零
		if ($userInfo['last_steal_time'] && $userInfo['last_steal_time'] < ($now-86400)) {
			$stealTimes = 0;
			$seriateStealParam = $G['seriate_steal_param'][0];
		} else {
			$stealTimes = $userInfo['seriate_steal_times'] + 1;
			if (isset($G['seriate_steal_param'][$userInfo['seriate_steal_times']])) {
				$seriateStealParam = $G['seriate_steal_param'][$userInfo['seriate_steal_times']];
			} else {
				$seriateStealParam = 0;
			}
		}
		
		
		if ($seriateStealParam) {
			$differenceLvl = abs($userInfo['lvl'] - $toUserInfo['lvl']);
			if (!isset($G['difference_lvl_steal_param'][$differenceLvl])) {
				$differenceLvl = 999;
			}
			$cropList = C('item/crop');
			$cfg = $cropList[$posInfo['now_crop']];
			$successRate = $G['base_steal_success_rate'][$cfg['lvl']]
							* $G['difference_lvl_steal_param'][$differenceLvl]
							* $G['seriate_steal_param'][$stealTimes]/10000;
			$success = getRandResult($successRate);
		} else {// 参数为0,肯定失败
			$success = false;
		}
		
		$DB->beginTransaction();
		$DB->setTransactionState(false);
		
		$result['data'] = array(
			'success' => $success
		);
		
		if ($success) {
			$addition = 0;
			foreach ($posInfo['num'] as $quality=>$num) {
				$addition += ($num * $G['steal_coin_prize_param'][$quality]);
			}
			// 获得金钱奖励
			$getCoin = $G['steal_coin_prize_base_value'] + $addition;
			$sql = 'UPDATE user SET coin=coin+'.$getCoin.',energy_point=energy_point-1,
					seriate_steal_times='.$stealTimes.',last_steal_time='.$now.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
			if ($ret) {
				$result['data']['get_coin'] = $getCoin;
			}
			
			if ($ret) {
				$sql = 'UPDATE farm SET is_stolen=1 WHERE fid='.$posInfo['fid'];
				$ret = $DB->exeSql($sql);
			}
			
		} else {
			// 关进监狱
			$ret = Prison::detain($uid);
			
			// 扣除能量点
			if ($ret) {
				$sql = 'UPDATE user SET energy_point=energy_point-1,
						seriate_steal_times=0,last_steal_time='.$now.' WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
			}
		}
		
		$DB->setTransactionState(true);

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_steal', $data);
		}
		return $result;
	}
	
	/**
	 * 除草
	 * @param $uid
	 * @param $to_uid 被除草的农田主人用户ID
	 * @param $pos 农田位置
	 */
	public static function weed($uid, $to_uid, $pos) 
	{
		global $DB, $L, $G;
		
		$userInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time,energy_point');
		// 能量点不够
		if (!$userInfo['energy_point']) {
			return array(
				'val' => false,
				'msg' => $L['energy_point_not_enough']
			);
		}
		
		// 判断是否好友
		if (!Friend::isFriend($uid, $to_uid)) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$posInfo = self::getPlowlandInfo($to_uid, $pos);
		// 只能成长状态可以除草
		if ($posInfo['status'] != 1) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 已经除过草了
		if ($posInfo['is_weeded']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$now = time();
		
		$DB->beginTransaction();
		$DB->setTransactionState(false);
		
		// 载入互动操作配置
		C('common/interactive');
		
		$cropList = C('item/crop');
		$cfg = $cropList[$posInfo['now_crop']];
		// 减少时间
		$reduceTime = round($cfg['plant_need_time'] * $G['weed_reduce_time']);
		$sql = 'UPDATE farm SET is_weeded=1,ripe_time=ripe_time-'.$reduceTime.' WHERE fid='.$posInfo['fid'];
		$ret = $DB->exeSql($sql);
		
		// 扣除能量点
		if ($ret) {
			$sql = 'UPDATE user SET energy_point=energy_point-1 WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		// 增加经验
		if ($ret) {
			$ret = User::addExp($uid, $G['weed_get_exp']);
		}
		
		$DB->setTransactionState(true);

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'info'		=> self::getPlowlandInfo($to_uid, $pos),
				'get_exp'	=> $G['weed_get_exp']
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('farm_weed', $data);
		}
		return $result;
	}

}





